package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;

import com.zzyl.nursing.util.AgeCalculator;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-13
 */
@Service
@Transactional
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;


    //老人模块
    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;


    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否已经入住
        //查询老人  通过身份证号查询
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
        queryWrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("老人已经入住");
        }

        //更新床位的状态  已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //保存或更新老人数据,返回值就是添加老人的所有消息
        elder = insertOrUpdate(bed,checkInApplyDto.getCheckInElderDto());

        //生成合同编号
        String contractNo  = "HT"+CodeGenerator.generateContractNumber();
        System.out.println(contractNo);

        //新增签约办理,添加合同
        insertContract(contractNo,elder,checkInApplyDto);

        //新增入住信息
        CheckIn checkIn = inserCheckIn(elder, checkInApplyDto);
        //新增入住配置信息
        insertCheckInConfig(checkIn.getId(),checkInApplyDto);

    }

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn inserCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        //将输入的入住配置信息填写到入住对象中
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }


    @Autowired
    private ContractMapper contractMapper;
    private void insertContract(String contractNo, Elder elder,CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        //属性拷贝,将输入的合同字段拷贝到合同对象中
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
//        设置编号
        contract.setContractNumber(contractNo);
        //状态、开始时间、结束时间
        //签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        //签约时间小于等于当前时间，合同生效中
        //设置状态
        int status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);

        //创建时间
        contract.setCreateTime(DateUtils.getNowDate());
        //结束时间
        contract.setEndDate(checkInEndTime);
        contract.setStartDate(checkInStartTime);
        //老人姓名
        contract.setElderName(elder.getName());
        //老人id
        contract.setElderId(elder.getId());
        //合同添加



        contractMapper.insert(contract);

    }


    /**
     * 新增或更新老人
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        //属性拷贝
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        //查询老人信息，（身份证号和状态  0）
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus,0);
        Elder elderDb  = elderMapper.selectOne(queryWrapper);

        if (ObjectUtil.isNotEmpty(elderDb)){
            //更新操作
            elderMapper.updateById(elder);
        }else{
            //新增操作
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }


    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        Long idd = checkIn.getId();
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInId(idd);
        if (checkInConfig == null){
            checkInConfig = new CheckInConfig();
        }
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        //查询老人的基本信息


        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //计算年龄
        int age = AgeCalculator.calculateAge(elder.getBirthday());
        System.out.println(age);
        if (age != -1) {
            checkInElderVo.setAge(age);
        }
        //   查询老人合同




        Contract contract = contractMapper.selectContractByEldreId(elderId);
        if (contract == null){
            contract = new Contract();
        }
//        家属响应信息
        String remark = checkIn.getRemark();
        if (remark == null){
            remark = "[]";
        }
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        System.out.println(elderFamilyVoList);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}
